﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSapce.ServiceLocation;
using SmartSpace.Web;
using SmartSpace.Workflow;

namespace SmartSpace.WebApp.Modules.Workflow
{
    public partial class Event_Create : SsTemplatePage
    {
        public Guid WorkflowId { get; private set; }
        public Guid ActivityId { get; private set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            WorkflowId = RequestUtility.GetGuid(Request, "wfid");
            ActivityId = RequestUtility.GetGuid(Request, "actid");
            //EventMetadata
            if (!IsPostBack)
            {
                IWorkflowService service = ServiceLocator.Get<IWorkflowService>();

                _ctlEditWorkflow.Text = service.GetWorkflow(WorkflowId).Data.Caption;
                _ctlEditActivity.Text = service.GetActivity(ActivityId).Data.Caption;

                SingleResult<ActivityMetadata> activity = service.GetActivity(ActivityId);

                ListResult<ActivityMetadata> activities = service.GetActivities(WorkflowId);
                _ctlListActivity.DataSource = activities.Data;
                _ctlListActivity.DataBind();
            }
        }

        protected void _ctlBtnSave_Click(object sender, EventArgs e)
        {
            IWorkflowService service = ServiceLocator.Get<IWorkflowService>();
            EventMetadata @event = new EventMetadata();
            @event.WorkflowId = WorkflowId;
            @event.Id = Guid.NewGuid();
            @event.FromActivityId = ActivityId;
            @event.ToActivityId = new Guid(_ctlListActivity.SelectedValue);
            if (@event.FromActivityId == @event.ToActivityId)
            {
                return;
            }
            @event.Code = _ctlEditCode.Text;

            @event.Caption = _ctlEditCaption.Text;

            if (service.SaveEvent(@event).IsSuccess)
            {
                Response.Redirect(string.Format("Activity-list.aspx?wfid={0}&actid={1}", WorkflowId, ActivityId));
            }
        }
    }
}